package com.last.listen;

import com.last.entity.Order;
import com.last.mapper.OrderMapper;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * <p>title: com.mq</p>
 * author zhuximing
 * description:
 */
@Service
@RocketMQMessageListener(consumerGroup = "es-consumer",
        topic = "order-delay",selectorExpression = "order-delay-tag",
        consumeMode = ConsumeMode.CONCURRENTLY,
        messageModel = MessageModel.CLUSTERING)
public class OrderDelayListen implements RocketMQListener<String> {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void onMessage(String orderId) {

        Order order = orderMapper.selectById(orderId);
        if(order.getOrderStatus() == 0){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            long start = Long.parseLong(simpleDateFormat.format(order.getStartDate()));
            long end = Long.parseLong(simpleDateFormat.format(order.getLeaveDate()));
            order.setOrderStatus(2);
            orderMapper.updateById(order);

            BoundHashOperations<String, String, String> stringObjectObjectBoundHashOperations = stringRedisTemplate.boundHashOps("roomId:" + order.getRoomId());
            Objects.requireNonNull(stringObjectObjectBoundHashOperations.keys()).forEach(k->{
                if(Long.parseLong(k) == start){
                    if(Long.parseLong(Objects.requireNonNull(stringObjectObjectBoundHashOperations.get(k))) == end){
                        stringObjectObjectBoundHashOperations.delete(k);
                    }
                }
            });
        }



    }
}